import React, { useCallback, useState } from 'react';
import classnames from 'classnames';
import { Form } from 'antd';
import { InputItem, TextareaItem, Picker, List, DatePicker, Switch } from 'antd-mobile';
import {LevelSelectItem} from '@/components'
import { formatDataToAntd } from '@/utils';
import _address from './formatAddress.json';
import _car from './formatCar.json';

import styles from './index.less';
import { stubFalse } from 'lodash';

const showRequired = (required?: boolean) => {
  if (required) return <span className="require-icon">*</span>;
  return '';
};
type ValidationRule = {
  /** validation error message */
  message?: React.ReactNode;
  /** built-in validation type, available options: https://github.com/yiminghe/async-validator#type */
  type?: string;
  /** indicates whether field is required */
  required?: boolean;
  /** treat required fields that only contain whitespace as errors */
  whitespace?: boolean;
  /** validate the exact length of a field */
  len?: number;
  /** validate the min length of a field */
  min?: number;
  /** validate the max length of a field */
  max?: number;
  /** validate the value from a list of possible values */
  enum?: string | string[];
  /** validate from a regular expression */
  pattern?: RegExp;
  /** transform a value before validation */
  transform?: (value: any) => any;
  /** custom validate function (Note: callback must be called) */
  validator?: (rule: any, value: any, callback: any, source?: any, options?: any) => any;
};
type ItemProps = {
  formType:
    | 'number'
    | 'text'
    | 'textarea'
    | 'select'
    | 'date'
    | 'brand-serie-spec'
    | 'brand-serie'
    | 'brand'
    | 'province-city-area'
    | 'province-city'
    | 'province'
    | 'input-chinese'
    | 'switch'
    | 'extra'
    | 'select-multiple';
  disabled?: boolean;
  name: string;
  label: string | React.ReactNode;
  required?: boolean;
  extra?: string | React.ReactNode;
  length?: number; // 输入框时 可选
  options?: any[]; // 下拉选 数据源，可以深层嵌套
  cols?: number; // 下拉选 联级层数
  fetchOptions?: (it: any) => void; // 下拉选点击时触发的方法,options如果有值则不会触发
  
  rules?: ValidationRule[];
  initialValue?: any;
  validateTrigger?: string | string[]; // 设置字段校验的时机
  valuePropName?: string; // 子节点的值的属性，如 Switch 的是 'checked'。该属性为 getValueProps 的封装，自定义 getValueProps 后会失效
  placeholder?: string;
};
interface RenderFormProps {
  textFormat?: (item: any,data:any) => void; 
  data: ItemProps[];
}
const RenderForm: React.FC<RenderFormProps> = (props) => {

  const {
    textFormat
  } =props
  const [switchChecked, setSwitchChecked] = useState(false);

  const renderCommonItem = useCallback((item) => {
    const {
      name,
      required,
      rules,
      label,
      initialValue,
      disabled,
      validateTrigger,
      valuePropName,
    } = item;
    return (component: React.ReactNode) => (
      <Form.Item
        className={classnames(styles['form-item'], { [styles['form-item-disabled']]: disabled })}
        initialValue={initialValue}
        // validateFirst
        key={name}
        validateTrigger={validateTrigger}
        valuePropName={valuePropName}
        name={name}
        // label={label}
        rules={
          required && !rules
            ? [
                {
                  required,
                  message: `${label}不能为空`,
                },
              ]
            : rules
        }
      >
        {component}
      </Form.Item>
    );
  }, []);
  /**
   * 文本formatf
   * @param item
   * @param data
   */
  const handleTextFormat = (item, data) => {
    if (typeof textFormat === 'function') {
      return textFormat(item, data);
    }
    if(item.formType==='brand-serie-spec' &&data.length===3){
      
      return data[2].carName
    }
    return '';
  };
  const format = useCallback((data: ItemProps[]) => {
    
    return data.map((item: ItemProps) => {
      const {
        formType,
        disabled,
        name,
        label,
        required,
        extra,
        length,
        options,
        cols,
        fetchOptions,
        initialValue,
        placeholder,
        
      } = item;
      // console.log('---', item)
      switch (formType) {
        case 'number': {
          console.log('initialValue->number', initialValue, name);
          return renderCommonItem(item)(
            <InputItem
              disabled={disabled}
              // onChange={it.onChange ? it.onChange : undefined}
              type="money"
              extra={extra}
              maxLength={length || undefined}
              placeholder={placeholder||'请输入'}
            >
              {showRequired(required)}
              {label}
            </InputItem>,
          );
        }
        case 'text': {
          // TextareaItem 需要值必须为string，number 需要转成 string
          console.log(name);
          return renderCommonItem(item)(
            <InputItem
              disabled={disabled}
              // onChange={it.onChange ? it.onChange : undefined}
              extra={extra}
              maxLength={length || undefined}
              placeholder={placeholder||'请输入'}
            >
              {showRequired(required)}
              {label}
            </InputItem>,
          );
        }
        case 'textarea': {
          // TextareaItem 需要值必须为string，number 需要转成 string
          console.log(name);
          return renderCommonItem({
            ...item,
            initialValue: typeof initialValue === 'number' ? `${initialValue}` : initialValue || '',
          })(
            <TextareaItem
              disabled={disabled}
              autoHeight
              title={
                <span>
                  {showRequired(required)}
                  {label}
                </span>
              }
              // onChange={it.onChange ? it.onChange : undefined}
              maxLength={length || undefined}
              placeholder={placeholder||'请输入'}
            >
              {showRequired(required)}
              {label}
            </TextareaItem>,
          );
        }
        case 'input-chinese': {
          return <input type="text" />;
        }
        case 'select': {
          return renderCommonItem(item)(
            <Picker
              data={options||[]}
              cols={cols || 1}
              disabled={disabled}
              title="请选择"
              extra={<span>{placeholder||'请选择'}</span>}
              
              // onChange={it.onChange ? it.onChange : undefined}
              onVisibleChange={(visible) => {
                if (visible && fetchOptions && !options) {
                  fetchOptions(item);
                }
              }}
            >
              <List.Item arrow="horizontal">
                {showRequired(required)}
                {label}
              </List.Item>
            </Picker>,
          );
        }
        case 'switch':{
          return <List.Item
          extra={<Switch checked={switchChecked} onChange={()=>setSwitchChecked(!switchChecked)}/>}
        >{showRequired(required)}{label}</List.Item>
        }
        case 'extra':{
          return <List.Item
          extra={extra}
        >{showRequired(required)}{label}</List.Item>
        }
        case 'select-multiple': {
          return <input type="text" />;
        }
        case 'date':{
          return renderCommonItem(item)( <DatePicker
          mode="date"
          title="请选择日期"
          format="YYYY-MM-DD"
          extra={<span>{placeholder||'请选择'}</span>}
        >
          <List.Item arrow="horizontal">{label}</List.Item>
        </DatePicker>)
        }
        case 'province':
        case 'province-city':
        case 'province-city-area': {
          return renderCommonItem(item)(
            <Picker
              data={formatDataToAntd(options||_address, 'name', 'areaId', 'children', true)}
              cols={formType.split('-').length}
              title="请选择"
              extra=" "
              format={(labels) => labels.join('-')}
              disabled={disabled}
              className={classnames({ 'text-disabled': disabled }, 'tttttttttttttt')}
              // onChange={it.onChange ? it.onChange : undefined}
            >
              <List.Item arrow="horizontal">
                {showRequired(required)}
                {label}
              </List.Item>
            </Picker>,
          );
        }
        case 'brand':
        case 'brand-serie':
        case 'brand-serie-spec': {
          return renderCommonItem(item)(
            <LevelSelectItem
            title={label}
            required={required}
            fetchData={(current, selected, value) =>
              typeof fetchOptions === 'function'
                ? fetchOptions({...item,current,value,selected})
                : () => []
            }
            textFormat={(data) => handleTextFormat(item, data)}
            
          />
          );
        }
        default: {
          return renderCommonItem(item)(
            <TextareaItem
              disabled={disabled}
              autoHeight
              title={
                <span>
                  {showRequired(required)}
                  {label}
                </span>
              }
              // onChange={it.onChange ? it.onChange : undefined}
              maxLength={length || undefined}
              // placeholder={`请填写`}
            >
              {label}
            </TextareaItem>,
          );
        }
      }
    });
  }, []);
  return <>{format(props.data)}</>;
};

export default RenderForm;
